package org.netty.udp.server.handler;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

public class UdpNettyServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
	
	private Logger logger = LoggerFactory.getLogger(UdpNettyServerHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
		String msg = packet.content().toString(Charset.forName("UTF-8"));
        logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " UDP server receive: " + msg);
        
        String json = "server received message !";
        // 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
        byte[] bytes = json.getBytes(Charset.forName("UTF-8"));
        DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), packet.sender());
        // 向客户端发送消息
        ctx.writeAndFlush(data);
	}
	
}
